package com.jeremy.comutils.utils;

import com.jeremy.comutils.domain.ComParamConfig;
import com.jeremy.comutils.domain.ATCmd;
import com.jeremy.comutils.exception.CustomComException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;

public class ATestUtils {
    //创建LOG对象
    private static final Logger logger = LogManager.getLogger();

    //统计出错次数
    private static int errorCount = 0;

    //统计出错发生处集合
    private static HashSet<Integer> errList = new LinkedHashSet<>();

    //ATFilesList读取流
    private static BufferedReader br;

    //加载ATList方法
    private static int loadATList(String line, String cmd, String res, String timeout, ArrayList<ATCmd> ATList, BufferedReader br, int lineNumber) throws IOException {
        int lineNumberCount = 0;
        for (int i = 0; i < lineNumber; i++) {
            line = br.readLine();
            if (line != null && !line.equals("")) {
                if (!line.startsWith("#")) {
                    String[] tmp = line.split("====");
                    cmd = tmp[0];
                    System.out.println("ATCmd = " + cmd);
                    res = tmp[1];
                    timeout = tmp[2];
                    ATCmd atCmd = new ATCmd(cmd, res, timeout);
                    ATList.add(atCmd);
                    lineNumberCount++;
                }
            }
        }
        return lineNumberCount;
    }

    //获取文件行数方法
    public static int getLineNumber(File file) {
        if (file.exists()) {
            try {
                FileReader fileReader = new FileReader(file);
                LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
                long skip = lineNumberReader.skip(Long.MAX_VALUE);
                int lines = lineNumberReader.getLineNumber() + 1;
                fileReader.close();
                lineNumberReader.close();
                return lines;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public static void run(String jeremyComPort, ArrayList<String> ATFilesList, int loopTimes) throws CustomComException, InterruptedException, IOException {
        System.out.println("\n" +
                "    /$$$$$ /$$$$$$$$ /$$$$$$$  /$$$$$$$$ /$$      /$$ /$$     /$$ /$$$$$$  /$$$$$$$$ /$$$$$$$$  /$$$$$$  /$$$$$$$$\n" +
                "   |__  $$| $$_____/| $$__  $$| $$_____/| $$$    /$$$|  $$   /$$//$$__  $$|__  $$__/| $$_____/ /$$__  $$|__  $$__/\n" +
                "      | $$| $$      | $$  \\ $$| $$      | $$$$  /$$$$ \\  $$ /$$/| $$  \\ $$   | $$   | $$      | $$  \\__/   | $$   \n" +
                "      | $$| $$$$$   | $$$$$$$/| $$$$$   | $$ $$/$$ $$  \\  $$$$/ | $$$$$$$$   | $$   | $$$$$   |  $$$$$$    | $$   \n" +
                " /$$  | $$| $$__/   | $$__  $$| $$__/   | $$  $$$| $$   \\  $$/  | $$__  $$   | $$   | $$__/    \\____  $$   | $$   \n" +
                "| $$  | $$| $$      | $$  \\ $$| $$      | $$\\  $ | $$    | $$   | $$  | $$   | $$   | $$       /$$  \\ $$   | $$   \n" +
                "|  $$$$$$/| $$$$$$$$| $$  | $$| $$$$$$$$| $$ \\/  | $$    | $$   | $$  | $$   | $$   | $$$$$$$$|  $$$$$$/   | $$   \n" +
                " \\______/ |________/|__/  |__/|________/|__/     |__/    |__/   |__/  |__/   |__/   |________/ \\______/    |__/   \n");
        System.out.println("-------【正在初始化ATList】-------");

        ArrayList<ATCmd> ATList = new ArrayList<>();
        String line = null;
        String cmd = null;
        String res = null;
        String timeout = null;
        for (String fileName : ATFilesList) {
            File file = new File("src/main/java/com/jeremy/comutils/cfg/" + fileName + ".txt");
            br = new BufferedReader(new FileReader(file));
            int fileLineNumber = getLineNumber(file);
            int loadNumber = loadATList(line, cmd, res, timeout, ATList, br, fileLineNumber);
            System.out.println("-------【ATList加载完成】：" + fileName + ".txt，共【" + loadNumber + "】条-------");
        }
        br.close();
        System.out.println("-------【ATList初始化完成】-------");

        // 实例化串口操作类对象
        SerialPortUtils serialPort = new SerialPortUtils();
        System.out.println("-------【正在测试的Air720COMPORT】 = " + jeremyComPort + "-------");
        // 创建串口必要参数接收类并赋值，赋值串口号，波特率，校验位，数据位，停止位
        ComParamConfig comParamConfig = new ComParamConfig(jeremyComPort, 115200, 0, 8, 1);
        // 初始化设置,打开串口，开始监听读取串口数据
        serialPort.init(comParamConfig);
        // 调用串口操作类的sendComm方法发送数据到串口
        for (int i = 0; i < loopTimes; i++) {
            for (ATCmd atCmd : ATList) {
                serialPort.sendComm(atCmd.getCmd() + "\r\n");
                Thread.sleep(Long.parseLong(atCmd.getTimeout()));
                String readRes = new String(serialPort.getData());
                serialPort.jeremyNotify();
                try {
                    if (readRes.contains(atCmd.getRes())) {
                        logger.trace((i + 1) + "命令【" + atCmd.getCmd() + "】结果匹配成功");
                    } else {
                        logger.error((i + 1) + "命令【" + atCmd.getCmd() + "】结果匹配失败");
                        errorCount += 1;
                        errList.add(i + 1);
                    }
                } catch (Exception e) {
                    System.out.println("-------【FATAL】你的模块很有可能没开机，或者正在执行的这个命令在指定的延迟时间内没有任何返回-------");
                    e.printStackTrace();
                    System.exit(0);
                }
            }
            logger.debug("第【" + (i + 1) + "】次测试完成，【ERROR】次数：" + errorCount + "，出错发生在第" + errList + "次");
        }
        // serialPort.readComm();
        // 关闭串口
        serialPort.closeSerialPort();
    }
}
